# -*- coding: utf-8 -*-
from math import atan, sqrt, pi, cos, sin
from table import Table

def fromXYToPolar(x1, y1, x2, y2):
    dx = float(x2 - x1)
    dy = float(y2 - y1)
    
    distance = round(sqrt(dx ** 2 + dy ** 2))
    
    if dx > 0:
        if dy >= 0:
            angle = atan(dy / dx)
        elif dy < 0:
            angle = atan(dy / dx) + 2 * pi
    elif dx < 0:
        angle = atan(dy / dx) + pi
    elif dx == 0:
        if dy > 0:
            angle = pi / 2
        elif dy < 0:
            angle = 3 * pi / 2
        elif dy == 0:
            angle = 0
    
    angle = round(angle * 3000 / pi) / 100
    
    return distance, angle

def fromPolarToXY(x1, y1, distance, angle):
    angle = angle * pi / 30
    dx = distance * cos(angle)
    dy = distance * sin(angle)
    x2 = round(x1 + dx)
    y2 = round(y1 + dy)
    return x2, y2

def fromHeightsToEpsilon(h1, h2, distance):
    return round(9.55 * (h2 - h1) / float(distance), 2)
    
def fromEpsilonToDh(epsilon, distance):
    return round(float(epsilon * distance) / 9.55)
    
if __name__ == '__main__':
    table = Table('tables/full.csv')
    Dk = 1800
    ak = 22.17
    knp = (43345, 87335)
    op = (43275, 82230)
    h1 = 148
    h2 = 130
    aon = 12
    corrections = (+180, -0.06)
    Fz = 0.70
    n = 6
    
    xz, yz = fromPolarToXY(knp[0], knp[1], Dk, ak)
    Dt, at = fromXYToPolar(op[0], op[1], xz, yz)
    print 'дальность ',Dt
    print 'направление ', at
    dt = aon - at
    epsilon = fromHeightsToEpsilon(h1, h2, Dt)
    level = 30 + epsilon
    Ky = round(Dk / Dt, 1)
    Wu = round(100 * (ak - at) / Dt, 2)
    
    Di = Dt + corrections[0]
    di = dt + corrections[1]
    Jb = round(Fz * Ky / n, 2)
    
    row = table.searchDistance(Di)
    print 'прицел ' + str(row.sight)
    print 'уровень ' + str(level)
    print 'направление ' + str(di)
    
#    xz,yz = fromPolarToXY(63660, 78020, 2200, 39.42)
#    print xz,yz
#    print fromXYToPolar(61365, 81745, xz, yz)
#    
    
    
